<?php
namespace app\zjs\controller;
use app\common\traits\Wechat;
//use app\common\traits\WechatZjs;
use Carbon\Carbon;
use think\Db;
use think\facade\Session;
use app\admin\model\Article;
use think\facade\Cache;
class Index extends Zjs
{
//    use WechatZjs;
    use Wechat;
    /**
     * @return mixed
     */
    public function _initialize(){

//        $this->traceHttp1();

//        if(input('echostr') && $this->checkSignature()){
//            echo  input('echostr');exit;
//        }

        parent::_initialize();
    }
    public function index()
    {
        if(Session::has('user_attr')){
            if(Session::get('user_attr')==153){//员工
                $where['cid']=2;
            }else{
                $where['cid']=1;
            }
        }
        $where['status'] =1;
        $where['is_top'] = 1;
        $article = Article::where($where)->order('sort')->find();
        $this->assign('article', $article);
        $this->getConfigs();
        $user_num = Db::name('customer')->where(['status'=>1])->count();
        $order_num = Db::name('orders')->count();
        $yongjin = $this->countYongjin();

        $this->assign('user_num',$user_num);
        $this->assign('order_num',$order_num);
        $this->assign('yongjin_count',$yongjin);
        return $this->fetch();
    }

    /**
     *设置活动
     */
    protected function getConfigs()
    {
        if (Cache::has('zjsconfigs')) {
            $zjsconfigs = Cache::get('zjsconfigs');
        } else {
            $zjsconfigs = config('zjs.huodong');
            if (!empty($zjsconfigs)) {
                Cache::set('zjsconfigs', $zjsconfigs,7200);
            }
        }
        $this->assign('huodong',$zjsconfigs);
    }

    protected function countYongjin(){
        $sum = 0;
        $now    = strtotime(Carbon::now()->startOfMonth());
        $time = '2017-11-01';
        $end = strtotime(Carbon::parse($time)->endOfMonth());
        $order_zjs_all = collect(Db::name('order')->where(['qd_depar'=>6,'ywstate'=>6])->field('id,tjr_id,cgpstime')->select());
        $users = Db::name('customer')->field('id')->select();
        for( $i=0;$end<$now;$i++ ){
            $begin = Carbon::parse($time)->addMonths($i);
            $start = strtotime($begin->startOfMonth()->toDateTimeString());
            $end1  = strtotime($begin->endOfMonth()->toDateTimeString());
            foreach ($users as $val){
                $num = $order_zjs_all->where('cgpstime','>=',$start)->where('cgpstime','<=',$end1)->where('tjr_id',$val['id'])->count();
                if( $num <5 ){
                    $sum += $num*20;
                }elseif($num>=5 && $num<10){
                    $sum += $num*25;
                }else{
                    $sum += $num*30;
                }
            }
            $begin = Carbon::parse($time)->addMonths($i+1);
            $end   = strtotime($begin->endOfMonth()->toDateTimeString());
        }
        return $sum;
    }
}
